<?php
require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/init.php';
/**
 *向pdm同步产品扩展属性
 *@author shipanpan
 */
class SynProductExtendController extends Controller_CronJob {
	public function run() {
		$response = $this->_getData();
		if ($response === false) {
			$errorMsg = $this->getErrorMsg();
			$this->log->record($errorMsg, Log::ERR);
			die($errorMsg);
		}

		$amountRow = $response['content']['totalCounts'];

		$pageLength = 500;
		$pageAmount = ceil($amountRow / $pageLength);
		for ($i = 1; $i <= $pageAmount; $i++) {
			$response = $this->_getData($i);
			if ($response === false) {
				$errorMsg = $this->getErrorMsg();
				$this->log->record($errorMsg, Log::ERR);
				continue;
			}

			$hasUpdateProducts = $response['content']['lists'];
			if (!is_array($hasUpdateProducts)) {
				continue;
			}
			foreach ($hasUpdateProducts as $_oneRow) {
				Model_Base::insertOrUpdate($this->writeDb, 'p_product_purchase_info', $_oneRow);
			}
		}
		$this->log->record('成功更新产品扩展属性！');
		die('成功更新产品扩展属性！');
	}

	protected function _getData($page = 1) {
		$pdmDomain = Helper_Config::get('url', 'pdm', 'url', null, true);
		$url = $pdmDomain . 'interface/product-extend/index';

		try {
			//每两个小时会同步一次，保险起见同步3小时有更新的记录
			$updateTime = time() - (3 * 60 * 60);
			$updateTime = date("Y-m-d H:i:s", $updateTime);
			$response = Controller_Interface::post($url, ['update_time' => $updateTime, 'page' => $page]);
		} catch (Exception $e) {
			$errorMsg = "获取产品扩展属性数据发生错误:" . $e->getMessage();
			return $this->_error($errorMsg);
		}

		$response = json_decode($response, true);
		if (!$response) {
			$errorMsg = "产品扩展属性数据格式异常,错误原因:" . json_last_error_msg();
			return $this->_error($errorMsg);
		}
		if ($response['opr'] != 1) {
			$errorMsg = "产品扩展属性数据发生错误,错误原因:" . $response['content'];
			return $this->_error($errorMsg);
		}

		return $response;
	}
}

$synProductExtendController = new SynProductExtendController();
$synProductExtendController->run();